package com.blacktea.behavioralpatterns.chainofresponsibilitypattern.config;

import com.blacktea.behavioralpatterns.chainofresponsibilitypattern.handler.RequestLogger;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Comparator;
import java.util.List;
import java.util.stream.IntStream;

/**
 * @description: 责任链配置
 * @author: black tea
 * @date: 2023/3/24 16:28
 */
@Configuration
@RequiredArgsConstructor
public class ChainOfResponsibilityPatternConfig {

    private final List<RequestLogger> loggers;

    @Bean
    public RequestLogger requestLogger(){
        loggers.sort(Comparator.comparingInt(RequestLogger::order));
        IntStream.range(0, loggers.size())
                .forEach(index -> {
                    RequestLogger current = loggers.get(index);
                    RequestLogger next = index < loggers.size() - 1 ? loggers.get(index + 1) : null;
                    if (next != null){
                        current.setNextHandler(next);
                    }
                });
        return loggers.get(0);
    }

}
